<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { createEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListAPI, updateEnterpriseAPI } from '@/apis/enterprise';
import type { EnterpriseListParams, EnterpriseParams, Industry } from '@/types/enterprise';
import { CircleCheck, Upload } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()
// 根据id判断是编辑还是添加
const id = computed(() => {
  return route.query.id as string
})
// 表单提交时，整体表单的校验
const formRef = ref<FormInstance>()
// 提交按钮loading状态
const submitLoading = ref(false)
const addForm = ref<EnterpriseParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: 0 ,// 营业执照id
}) 
const addRules = ref<FormRules<EnterpriseParams>>({
  name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '请输入法人', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '请输入注册地址', trigger: 'blur' }
  ],


  industryCode: [
    { required: true, message: '请选择行业', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  businessLicenseUrl: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ],
  businessLicenseId: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ]

})
const industryList = ref<Industry[]>([])
const getIndustryList = async () => {
  const res = await getIndustryListAPI()
  // console.log(res);
  industryList.value = res.data
}
getIndustryList()

const fileList = ref<UploadUserFile[]>([])

// 自定义上传
// http-request	  	覆盖默认的 Xhr 行为，允许自行实现上传文件的请求。 
// 鼠标悬停http-request   TS类型：(options: UploadRequestOptions) => XMLHttpRequest | Promise<unknown>
const onUploadRequest = async (options: UploadRequestOptions) => {
  // console.log('options', options);
  // 1. 准备 FormData 对象
  const fd = new FormData()
  // 2. 根据后端要求准备字段
  fd.append('file', options.file)
  fd.append('type', 'businessLicense')
  // 3. 调用接口上传文件
  const res = await uploadAPI(fd)
  // 保存营业执照的url id
  addForm.value.businessLicenseUrl = res.data.url
  addForm.value.businessLicenseId = res.data.id
  // 主动触发校验
  formRef.value?.validateField('businessLicenseUrl')
  // 4. 检查上传结果
  // console.log('res', res.data.url);
  return res.data.url
}
// 在before-upload钩子中限制文件的格式和大小
const beforeUpload = (rawFile: UploadRawFile)=>{
  // size 限制文件大小，单位为字节
  // 5M = 5 * 1024 * 1024
  if(rawFile.size > 5 * 1024 * 1024){
    ElMessage.error('上传文件不能大于5M')
    return false
  } else if(['image/jpeg', 'image/png'].includes(rawFile.type)===false){
    ElMessage.error('图片格式不正确，请重新上传')
    return false
  }
}

// 确认提交按钮
const onSubmit = async () => {
  try {
    if(id.value){
      await updateEnterpriseAPI({
        ...addForm.value,
        id: id.value
      })
    }else{
      await formRef.value?.validate()
    // 按钮变成loading状态,防止多次点击提交
    submitLoading.value = true
    // 提交表单
    await createEnterpriseAPI(addForm.value)
    // 提示信息
    ElMessage.success('添加成功')
    }
    // 跳转回列表页
    router.back()
  } catch {
    // 按钮重置
    submitLoading.value = false
  }
}
// 重置按钮
const onReset = () => {
  formRef.value?.resetFields()
}
// 删除上传文件
const removeUpload = () => {
 addForm.value.businessLicenseUrl = ''
 addForm.value.businessLicenseId = undefined
 formRef.value?.validateField('businessLicenseUrl')
}
// 回显数据
const getEnterpriseDetail = async () => {
  const res = await getEnterpriseDetailAPI(id.value)
  const { businessLicenseUrl, businessLicenseId, contact, contactNumber, industryCode, legalPerson, name, registeredAddress, businessLicenseName } = res.data
  addForm.value = {
    businessLicenseUrl,
    businessLicenseId,
    contact,
    contactNumber,
    industryCode,
    legalPerson,
    name,
    registeredAddress,
  }
  fileList.value.push({
    name: businessLicenseName,
    url: businessLicenseUrl,
  })
}
// 挂载时回显数据
onMounted(() => {
  if(id.value){
    getEnterpriseDetail()
  }
})
</script>


<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content="id?'编辑企业' :'添加企业'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="formRef" label-width="100px"
          :model="addForm"
          :rules="addRules"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input 
              :disabled="Boolean(id)"
              v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" clearable>
              <el-option v-for="item in industryList" :key="item.industryCode" 
                :value="item.industryCode"
                :label="item.industryName" />
                <!-- value给后端看 label 给用户看 -->
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber" >
              <el-input v-model="addForm.contactNumber" maxlength="11" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <!-- :http-request 自定义上传函数 -->
              <el-upload 
              :http-request="onUploadRequest" 
              list-type="picture"
              :limit="1"
              accept="..png,.jpeg,.jpg"
              :before-upload="beforeUpload"
              v-model:file-list="fileList"
              @remove="removeUpload"
              >
                <el-button v-if="fileList.length===0" :icon="Upload" type="primary"> 
                  点击上传</el-button>
                  <el-button v-else :icon="CircleCheck" type="success"disabled> 
                    已上传
                    </el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 jpg/png 文件， 大小不超过5MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset()" :disabled="Boolean(id)">重置</el-button>
        <el-button @click="onSubmit()" :loading="submitLoading" type="primary">确定</el-button>
      </div>
      {{ addForm }}
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>